package com.company.graph;

public class 岛屿的最大面积 {

    public static void main(String[] args) {
        int[][] map = {
                {0,0,1,0,0,0,0,1,0,0,0,0,0},
                {0,0,0,0,0,0,0,1,1,1,0,0,0},
                {0,1,1,0,1,0,0,0,0,0,0,0,0},
                {0,1,0,0,1,1,0,0,1,0,1,0,0},
                {0,1,0,0,1,1,0,0,1,1,1,0,0},
                {0,0,0,0,0,0,0,0,0,0,1,0,0},
                {0,0,0,0,0,0,0,1,1,1,0,0,0},
                {0,0,0,0,0,0,0,1,1,0,0,0,0}};
        System.out.println(new 岛屿的最大面积().maxAreaOfIsland(map));
    }

    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;

        int row = grid.length;
        int col = grid[0].length;

        boolean[][] visited = new boolean[row][col];
        int maxIsland = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1) {
                    maxIsland = Math.max(maxIsland,dfs(grid,i,j,visited));
                }
            }
        }

        return maxIsland;
    }

    final static int[][] Ds = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};

    public int dfs(int[][] grid,int x,int y,boolean[][] visited){

        final int row = grid.length;
        final int col = grid[0].length;

        if (x < 0 || x >= row || y < 0 || y >= col) {
            return 0;
        }
        if (grid[x][y] == 0 || visited[x][y]) {
            return 0;
        }

        visited[x][y] = true;

        int res = 1;

        for (int[] d : Ds) {
            res += dfs(grid,x + d[0],y + d[1], visited);
        }

        return res;
    }

}
